package com.jx.gocomtask.webservice.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;
import java.util.stream.Collectors;
import static java.util.Comparator.comparing;

import javax.annotation.Resource;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import com.jx.gocomtask.utils.JacksonUtil;
import com.jx.gocomtask.webservice.DTO.GroupPostMessage;
import com.jx.gocomtask.webservice.DTO.StatusMessage;
import com.jx.gocomtask.webservice.DTO.TaskScope;
import com.jx.gocomtask.webservice.DTO.TaskStatus;
import com.jx.gocomtask.webservice.DTO.TodoStatus;
import com.jx.gocomtask.webservice.DTO.UserInfoList;
import com.jx.gocomtask.webservice.DTO.UserInfoList.UserInfo;
import com.jx.gocomtask.webservice.entity.ExtRemindPlan;
import com.jx.gocomtask.webservice.entity.ExtTaskMessage;
import com.jx.gocomtask.webservice.entity.ExtTaskTodo;
import com.jx.gocomtask.webservice.entity.ExtTaskTodoUser;
import com.jx.gocomtask.webservice.entity.ExtTaskUser;
import com.jx.gocomtask.webservice.repository.ExtTaskMessageHistoryRepository;
import com.jx.gocomtask.webservice.repository.ExtTaskMessageRepository;
import com.jx.gocomtask.webservice.repository.ExtTaskTodoRepository;
import com.jx.gocomtask.webservice.service.GroupService;
import com.jx.gocomtask.webservice.service.Route;
import com.jx.gocomtask.webservice.service.RouteExt;
import com.jx.gocomtask.webservice.service.SendMessageService;
import com.jx.gocomtask.webservice.service.SystemSuperApp;
import com.jx.gocomtask.webservice.service.impl.RouteService.Segment;
import com.jx.gocomtask.webservice.task.RepeatPlan;
@Service
public class RouteExtService implements RouteExt{
	private static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(RouteExtService.class);
	@Resource(name="apiurl")
	String gocomeApiUrl;
	@Resource(name="serviceUrl")
	String serviceUrl;
	@Resource(name="serviceIosUrl")
	String serviceIosUrl;
	@Resource(name="serviceAndroidUrl")
	String serviceAndroidUrl;
	@Resource(name="defaultAppId")
	String defaultAppId;
	@Resource(name="defaultGroupAppId")
	String  defaultGroupAppId;
	@Autowired
	RestTemplate restTemplate;
	@Autowired
	SystemSuperApp systemSuperApp;
	@Resource
	GroupService groupService;
	@Autowired
	ExtTaskMessageRepository extTaskMessageRepository;
	@Resource
	SendMessageService sendMessageService;
	@Autowired
	ExtTaskTodoRepository extTaskTodoRepository;
	@Autowired
	RepeatPlan repeatPlan;
	@Autowired
	ExtTaskMessageHistoryRepository extTaskMessageHistoryRepository;
	@Override
	public ExtTaskMessage copyExtTaskMessagePlan(ExtTaskMessage extTask,ExtTaskMessage props,Route route) {
		ExtTaskMessage extTaskMessage = new ExtTaskMessage();
		BeanUtils.copyProperties(extTask,extTaskMessage);
		BeanUtils.copyProperties(props,extTaskMessage);
		String uuid = UUID.randomUUID().toString();
		extTaskMessage.setId(null);
		extTaskMessage.setUuid(uuid);
		extTaskMessage.setStatus(TaskStatus.START);
		extTaskMessage.setIos(serviceIosUrl+"&taskId="+uuid);
		extTaskMessage.setUrl(serviceUrl+"&taskId="+uuid);
		extTaskMessage.setAndroid(serviceAndroidUrl+"&taskId="+uuid);
		extTaskMessage.setStatusMessage(route.changeContent(extTaskMessage));
		extTaskMessage.setExtRemindPlan(null);
	    route.preSaveExtTaskMessage(extTaskMessage);
		//extTaskMessage.getExtTaskUser().clear();
		extTaskMessage.setExtTaskUser(extTask.getExtTaskUser().stream().map(this::converterExtTaskUser).collect(Collectors.toList()));
		extTaskMessage.getExtTaskUser().forEach(e->e.setExtTaskMessage(extTaskMessage));
		
		repeatPlan.createRemindPlan(extTaskMessage);
		return extTaskMessageRepository.save(extTaskMessage);
	}
	private ExtTaskUser converterExtTaskUser(ExtTaskUser extTaskUser){
		ExtTaskUser extTaskUser_=new ExtTaskUser();
		BeanUtils.copyProperties(extTaskUser,extTaskUser_);
		extTaskUser_.setId(null);
		extTaskUser_.setStatus(TaskStatus.START);  
		extTaskUser_.setExtTaskUserHistories(null);
		return extTaskUser_;  
	}
	@Override
	public ExtTaskMessage saveExtTaskMessagePlan(ExtTaskTodo extTaskTodo,Route route, boolean isfinish) {
		ExtTaskMessage extTaskMessage = new ExtTaskMessage();
		extTaskMessage.setGroup(extTaskTodo.getGocomGroup());
		extTaskMessage.setFrom(extTaskTodo.getFromDevice());
		extTaskMessage.setMessageType(extTaskTodo.getMessageType());
		extTaskMessage.setFromUser(extTaskTodo.getFromUser());
		extTaskMessage.setFromUserTrueName(extTaskTodo.getFromUserName());
		extTaskMessage.setScope(extTaskTodo.getScope());
		extTaskMessage.setContent(extTaskTodo.getContent());
		extTaskMessage.setStatus(isfinish?TaskStatus.OVER:TaskStatus.START);
		extTaskMessage.setExecPlan(extTaskTodo.getExecPlan()) ;
		extTaskMessage.setIsRemind(extTaskTodo.getIsRemind()) ;
		extTaskMessage.setDeadline(extTaskTodo.getDeadline()) ;
		extTaskMessage.setIsRepeat(extTaskTodo.getIsRepeat()) ;
		extTaskMessage.setWorkMode(extTaskTodo.getWorkMode()) ;
		extTaskMessage.setLabel(extTaskTodo.getLabel()) ;

		String uuid = UUID.randomUUID().toString();
		extTaskMessage.setUuid(uuid);
		extTaskMessage.setIos(serviceIosUrl+"&taskId="+uuid);
		extTaskMessage.setUrl(serviceUrl+"&taskId="+uuid);
		extTaskMessage.setAndroid(serviceAndroidUrl+"&taskId="+uuid);
		List<ExtTaskUser> userLinkedList = new LinkedList<ExtTaskUser>();
		List<ExtTaskTodoUser> todouserLinkedList = extTaskTodo.getExtTaskTodoUsers();
		if(todouserLinkedList!=null){
			for(ExtTaskTodoUser extTaskTodoUser:todouserLinkedList){
				ExtTaskUser taskUser = new ExtTaskUser();
				taskUser.setExtTaskMessage(extTaskMessage);
				taskUser.setTaskUser(extTaskTodoUser.getTaskUser());
				taskUser.setTaskUserName(extTaskTodoUser.getTaskUserName());
				taskUser.setStatus(isfinish?TaskStatus.FINISHED:TaskStatus.START);
				userLinkedList.add(taskUser);
			}
		}
		extTaskMessage.setExtTaskUser(userLinkedList);
		extTaskMessage.setStatusMessage(route.changeContent(extTaskMessage));
		extTaskMessage = route.preSaveExtTaskMessage(extTaskMessage);
		repeatPlan.createRemindPlan(extTaskMessage);
		extTaskTodo.setTodoStatus(TodoStatus.TASK);
		ExtTaskMessage extTaskMessage_rt =extTaskMessageRepository.save(extTaskMessage);
		extTaskTodo.setMessageId(extTaskMessage_rt.getId());
		extTaskTodoRepository.save(extTaskTodo);
		extTaskMessageHistoryRepository.updateTodoHistory(extTaskMessage_rt.getId(),extTaskTodo.getId());
		return extTaskMessage_rt;
	}
	@Override
	public ExtTaskMessage saveExtTaskMessage(ExtTaskTodo extTaskTodo,Route route, boolean isfinish) {
		ExtTaskMessage extTaskMessage = new ExtTaskMessage();
		GroupPostMessage postMessage=new GroupPostMessage();
		postMessage.setGroup(extTaskTodo.getGocomGroup());
		postMessage.setFrom(extTaskTodo.getFromDevice());
		postMessage.setMsgType(extTaskTodo.getMessageType());
		postMessage.setFromUserName(extTaskTodo.getFromUser());
		extTaskMessage.setGroup(postMessage.getGroup());
		extTaskMessage.setFrom(postMessage.getFrom());
		extTaskMessage.setMessageType(postMessage.getMsgType());
		extTaskMessage.setFromUser(postMessage.getFromUserName());
		extTaskMessage.setFromUserTrueName(extTaskTodo.getFromUserName());
		extTaskMessage.setScope(extTaskTodo.getScope());
		extTaskMessage.setContent(extTaskTodo.getContent());
		extTaskMessage.setStatus(isfinish?TaskStatus.OVER:TaskStatus.START);

		String uuid = UUID.randomUUID().toString();
		extTaskMessage.setUuid(uuid);
		extTaskMessage.setIos(serviceIosUrl+"&taskId="+uuid);
		extTaskMessage.setUrl(serviceUrl+"&taskId="+uuid);
		extTaskMessage.setAndroid(serviceAndroidUrl+"&taskId="+uuid);
		List<ExtTaskUser> userLinkedList = new LinkedList<ExtTaskUser>();
		List<ExtTaskTodoUser> todouserLinkedList = extTaskTodo.getExtTaskTodoUsers();
		List<UserInfoList.UserInfo> userInfoList=new ArrayList<>();
		if(todouserLinkedList!=null){
			for(ExtTaskTodoUser extTaskTodoUser:todouserLinkedList){
				ExtTaskUser taskUser = new ExtTaskUser();
				UserInfoList.UserInfo uu=new UserInfoList.UserInfo();
				taskUser.setExtTaskMessage(extTaskMessage);
				taskUser.setTaskUser(extTaskTodoUser.getTaskUser());
				taskUser.setTaskUserName(extTaskTodoUser.getTaskUserName());
				uu.setUserid(extTaskTodoUser.getTaskUser());
				uu.setTruename(extTaskTodoUser.getTaskUserName());
				userInfoList.add(uu);
				taskUser.setStatus(isfinish?TaskStatus.FINISHED:TaskStatus.START);
				userLinkedList.add(taskUser);
			}
		}
		extTaskMessage.setExtTaskUser(userLinkedList);
		extTaskMessage.setPostMessage(postMessage);
		extTaskMessage.setStatusMessage(route.changeContent(extTaskMessage));
        //		发送消息
		extTaskMessage = route.preSaveExtTaskMessage(extTaskMessage);
		 return extTaskMessageRepository.save(extTaskMessage);
		
	}

	@Override
	public void saveExtTaskTodo(GroupPostMessage postMessage,Route route, List<Segment> segments, String form) {
		TaskScope taskScope = TaskScope.OTHER;
		if("ALL".equals(form)) {
			String url = gocomeApiUrl + "groupapp/group/member/list?" + systemSuperApp.appid_token(defaultGroupAppId);
			taskScope = TaskScope.ALL;
			url = url + "&groupid=" + postMessage.getGroup();
			String rt = restTemplate.postForObject(url, null, String.class);
			List<UserInfoList.UserInfo> userinfo_s = JacksonUtil.toList(rt, UserInfoList.UserInfo.class);
			//过滤掉自己
			userinfo_s=userinfo_s.stream().filter(t->!t.getUserid().equals(postMessage.getFromUserName())).collect(Collectors.toList());
			for(Segment segment :segments){
				int ttage=0;
				List<UserInfo> userInfos =segment.getSameUserInfo();
				for(UserInfo userInfo : userInfos){
					if(userInfo.getUserid().equals("all")){
						segment.setTaskScope(TaskScope.ALL);
						ttage++;
						break;
					}
				}
				if(ttage>0){
					userInfos.clear();
					userInfos.addAll(userinfo_s);
				}
			}
			//segments.get(0).getSameUserInfo().addAll(userinfo_s);
		}
		if("ONESELF".equals(form)){
			taskScope = TaskScope.MYSELF;
			segments.get(0).setTaskScope(TaskScope.MYSELF);
		}
			//taskScope = TaskScope.MYSELF;
		List<ExtTaskTodo> messageList = new LinkedList<>();
		for(Segment segment : segments) {
			ExtTaskTodo extTaskTodo =new ExtTaskTodo();
			extTaskTodo.setContent(segment.getText());
			extTaskTodo.setFromDevice(postMessage.getFrom());
			extTaskTodo.setMsgId(postMessage.getMsgId());
			extTaskTodo.setFromUser(postMessage.getFromUserName());
			extTaskTodo.setFromUserName(route.takeUserInfo(postMessage.getFromUserName()));
			extTaskTodo.setGocomGroup(postMessage.getGroup());
			extTaskTodo.setMessageType(postMessage.getMsgType());
			extTaskTodo.setStatus(TaskStatus.START);
			extTaskTodo.setTodoStatus(TodoStatus.START);
			extTaskTodo.setScope(segment.getTaskScope());
			List<ExtTaskTodoUser> userLinkedList = new LinkedList<ExtTaskTodoUser>();
			for(UserInfoList.UserInfo userInfo : segment.getSameUserInfo()) {
				if(null == userInfo.getUsername())
					userInfo.setUsername(userInfo.getTruename().replace("@", ""));
				ExtTaskTodoUser extTaskTodoUser =new ExtTaskTodoUser();
				extTaskTodoUser.setExtTaskTodo(extTaskTodo);
				extTaskTodoUser.setTaskUser(userInfo.getUserid());
				extTaskTodoUser.setTaskUserName(userInfo.getUsername());
				userLinkedList.add(extTaskTodoUser);
			}
			extTaskTodo.setExtTaskTodoUsers(userLinkedList);
			messageList.add(extTaskTodo);
		}
		extTaskTodoRepository.save(messageList);
	}
	
}
